package com.demo.base.tokenLogin.resolver;

import com.demo.base.exception.AiException;
import com.demo.base.tokenLogin.annotation.CurrentUser;
import com.demo.base.tokenLogin.model.UserDto;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import static com.demo.constants.AppConstants.APP_REQUEST_ATTRIBUTE;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description * 自定义配套解析器 * 把当前登录用户信息实例化到User * 将request获得的用户信息返回给@CurrentUser
 * @date 2023/3/13 3:22 PM
 */
public class CurrentUserResolver implements HandlerMethodArgumentResolver {

    /**
     * 用于判断是否支持对某种参数的解析
     *
     * @param parameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserDto.class)
                && parameter.hasParameterAnnotation(CurrentUser.class);
    }

    /**
     * 将请求中的参数值解析为某种对象 将User数据传递给@CurrentUser
     *
     * @param parameter
     * @param mavContainer
     * @param webRequest
     * @param binderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(
            MethodParameter parameter,
            ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest,
            WebDataBinderFactory binderFactory)
            throws Exception {

        // 返回用户信息到currentUser注解
        UserDto user =
                (UserDto)
                        webRequest.getAttribute(
                                APP_REQUEST_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
        if (user != null) {
            return user;
        }

        // 未获取到用户信息，抛出异常
        throw new AiException("请求失败，请检查登录状态");
    }
}
